package zmee.pur.src.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import zmee.bid.oa.OAutil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

/**
 * @Author: xw
 * @Date: 2022/12/12/16:15
 * @Description: 标书编制设置评标方式、评分计算规则和评分方案设置，同时支持公告的发起，招标预算金额的回写
 */
public class PurListStandBillPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void registerListener(EventObject e) {
        BasedataEdit oaorg=this.getControl("oaorg");
        oaorg.addBeforeF7SelectListener(this);
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        Object aosqr = this.getModel().getValue("aosqr");
        if(aosqr==null) {
            DynamicObject user = BusinessDataServiceHelper.loadSingle(UserServiceHelper.getCurrentUserId(), "bos_user");
            this.getModel().setValue("aosqr", user);
            DynamicObjectCollection entryentity = user.getDynamicObjectCollection("entryentity");
            DynamicObject userOrg = OAutil.getUserOrg(entryentity);
            this.getModel().setValue("oaorg", userOrg.getDynamicObject("dpt"));
        }


        BigDecimal tempMoney = (BigDecimal) this.getModel().getValue("money");
        if (tempMoney.compareTo(new BigDecimal("0")) != 0) {
            return;
        }
        //原单ID
        Object srcBillId = this.getModel().getValue("srcbillid");
        if (StringUtils.isBlank(srcBillId)) {
            return;
        }
        //查询招标立项申请单
        DynamicObject demand = BusinessDataServiceHelper.loadSingle(srcBillId, "src_demand");
        //本次招标预算金额
        BigDecimal money = demand.getBigDecimal("money");
        this.getModel().setValue("money", money);
        //【评标方式】设定下拉枚举值：线上评标、线下评标，默认线上评标
        this.getModel().setValue("zmee_scoretype1", "1");
        //【评分方式】设定下拉枚举值：百分制(每个指标按百分制评分，方案=100分)、
        // 实际值(每个指标按实际值评分，方案=100分)、最终值(每个指标按最终值评分，方案<100分)，
        // 默认最终值(每个指标按最终值评分，方案<100分)
        this.getModel().setValue("zmee_scoremethod1", "3");
        String sourceTypeNumber = ((DynamicObject) this.getModel().getValue("sourcetype")).getString("number");
        if ("C010405".equals(sourceTypeNumber)) {
            this.getModel().setValue("zmee_ispaper", true);
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent event) {
        String name = event.getProperty().getName();
        if("oaorg".equals(name)){
            Object aosqr = this.getModel().getValue("aosqr");
            if(aosqr==null){
                event.setCancel(true);
                this.getView().showTipNotification(ResManager.loadKDString("请先选择申请人。", "PurListStandBillPlugin", "pur-src-formplugin", new Object[0]));
                return;
            }
            DynamicObject  sqr=(DynamicObject)aosqr ;
            DynamicObject user = BusinessDataServiceHelper.loadSingle(sqr.getPkValue(), "bos_user");
            DynamicObjectCollection entryentity = user.getDynamicObjectCollection("entryentity");
            List<QFilter> list=new ArrayList<>();
            String[] str=new String[entryentity.size()];
            for (int i = 0; i < entryentity.size(); i++) {
                str[i]=entryentity.get(i).getString("dpt.id");
            }
            QFilter qFilter=new QFilter("id", QCP.in,str);
            list.add(qFilter);
            event.setCustomQFilters(list);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        ChangeData change = e.getChangeSet()[0];
        Object newValue = change.getNewValue();
        if("aosqr".equals(name)){
            if(newValue==null) {
                return;
            }
           DynamicObject sqr=(DynamicObject)newValue;
           DynamicObject user = BusinessDataServiceHelper.loadSingle(sqr.getPkValue(), "bos_user");
           DynamicObjectCollection entryentity = user.getDynamicObjectCollection("entryentity");
           DynamicObject userOrg = OAutil.getUserOrg(entryentity);
           this.getModel().setValue("oaorg",userOrg.getDynamicObject("dpt"));
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        if ("audit".equals(operateKey)) {
            if (args.getOperationResult().isSuccess()) {
                //原单ID
                Object srcBillId = this.getModel().getValue("srcbillid");
                if (StringUtils.isBlank(srcBillId)) {
                    return;
                }
                //查询招标立项申请单
                DynamicObject demand = BusinessDataServiceHelper.loadSingle(srcBillId, "src_demand");
                BigDecimal money = (BigDecimal) this.getModel().getValue("money");
                demand.set("zmee_amountmoney", money);
                SaveServiceHelper.update(new DynamicObject[]{demand});
            }
        } else if ("scheme".equals(operateKey)) {
            ListShowParameter showParameter = new ListShowParameter();
            showParameter.setFormId("bos_treelist");
            showParameter.setBillFormId("src_scheme");
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(showParameter);
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        FormOperate formOperate=(FormOperate)args.getSource();
        String key = formOperate.getOperateKey();
        if("save".equals(key)||"submit".equals(key)){
            String billno = (String) this.getModel().getValue("billno");
            //项目启动
            DynamicObject project = BusinessDataServiceHelper.loadSingle("src_project", "id", new QFilter("billno", QCP.equals, billno).toArray());
            //中标原则
            DynamicObject projectRule = BusinessDataServiceHelper.loadSingle("src_project_rule", "id,scheme,scheme.ranktype", new QFilter("parentid", QCP.equals, project.getPkValue()).toArray());
            this.getModel().setValue("taxtypepm",projectRule.getString("scheme.ranktype"));
        }
    }

}
